/**
 * Created by King_Vicent on 2018/7/21.
 */
var dqurl = '../../'
var vm = new Vue({
    el: '#rrapp',
    data () {
        return {
            isAdd: false, // 新增指令内容显隐切换
            isList: true, // 默认状态
            isDetail: false, // 查看详情
            tableData: [], // 获取表格数据
            pageNo: 1, // 当前页
            totalPage: 0, // 总页数
            pageSize: 10, // 每页数据条数
            pageTitle: '新增指令', // 块标题
            findKey: '', // 搜索关键字
            dwType: 0, // 选择条线单位或非条线单位
            baseForm: {
                titleName: '', // 立项标题
                msgFlag: 0, // 是否短信通知
                zlxq: '', // 指令详情
                level: '', // 紧急度
                hysj: '', // 截止时间
                ids: [], // 选中单位的id
                zlzt: 0 // 指令状态
            },
            formPersonList: [], // 选中的人员
            fbfwList: [], // 单位列表
            fbfwCheckedList: [], // 选中单位
            nowCheckedDw: '未选择单位', // 当前选中单位名称
            fbfwPersonList: [], // 单位下属人员
            fbfwCheckedPersonList: [], // 选中人员
            tplKindList: [], // 模板类别列表
            tplViewList: [], // 模板预览列表
            props: {
                children: 'children',
                label: 'label'
            },
            tplId: '', // 所选模板的id
            levelOptions: [ // 紧急度选项
                {
                    value: '0',
                    label: '普通'
                },
                {
                    value: '1',
                    label: '紧急'
                }
            ],

            // 查看
            instructionsId: '', // 被查看的指令的id
            targetId: '', // 被查看的指令的对象id
            instructionsTitle: '', // 详情标题
            instructionsTime: '', // 详情会议时间
            instructionsUpdateTime: '', // 详情创建时间
            instructionsCorp: '', // 详情单位
            instructionsStatus: '',// 详情状态
            itemInfos: '',// 指令详情
            qswd: [], // 签收记录
            amountDw: '0', // 签收单位总个数
            checkedDw: '0', // 已签收个数
            checkedDWData: [], // 已签收单位
            unCheckedDWData: [], // 未签收单位
        }
    },
    mounted () {
    	//this.handleView(0,53)
    	var id = $("#id").val();
    	if(id == ''){
    		this.getData()
    	}
    },
    methods: {
        // 获取数据
        getData () {
            // 接口获取数据后对baseForm对象中对应的字段赋值，字段已经绑定页面对应的表单部分
            $.ajax({
                type: "GET",
                url: dqurl + 'business/instructions/list',
                contentType: "application/json",
                success: function (res) {
                    if (res.code === '0') {
                        vm.tableData = res.page.list
                        vm.totalPage = res.page.totalPage
                        vm.pangeNo = res.page.currPage
                    } else {
                        alert(res.msg);
                    }
                }
            });
        },

        // 搜索
        search () {
            let params = {
                'titleName': vm.findKey,
            }
             $.ajax({
                 type: "post",
                 url: dqurl + 'business/instructions/list',
                 data: params,
                 //contentType: "application/json",
                 success: function (res) {
                     if (res.code === '0') {
                         vm.tableData = res.page.list
                         vm.totalPage = res.page.totalPage
                         vm.pangeNo = res.page.currPage
                     } else {
                         alert(res.msg);
                     }
                 }
             });
        },
        indexMethod(index){
            return (vm.pageNo - 1) * vm.pageSize + (index + 1);
        },
        // 分页
        pageChange: function () {
            let params = {
            	'titleName': vm.findKey,
                'page': vm.pageNo
            }
            // $.ajax({
            //     type: "POST",
            //     url: baseURL + 'business/superviseproject/list',
            //     dataType: 'json',
            //     data: params,
            //     success: function (res) {
            //         if (res.code === '0') {
            //             vm.tableData = res.page.list
            //             vm.totalPage = res.page.totalPage
            //             vm.pangeNo = res.page.currPage
            //         } else {
            //             alert(res.msg);
            //         }
            //     }
            // });
            $.ajax({
                type: "GET",
                url: dqurl + 'business/instructions/list',
                contentType: "application/json",
                data:params,
                success: function (res) {
                    if (res.code === '0') {
                        vm.tableData = res.page.list
                        vm.totalPage = res.page.totalPage
                        vm.pangeNo = res.page.currPage
                    } else {
                        alert(res.msg);
                    }
                }
            });
        },

        // 过滤状态
        formatStatus (status) {
            switch(status.receiveStatus){
                case '0' : return '未签收';
                case '1' : return '已签收';
                case '2' : return '已完成';
                case '3' : return '进行中';
                default : return '未知';
            }
        },

        // 过滤重要程度
        formatLevel (level) {
            return level.level === '1'? '紧急' : '普通'
        },
        filterLevel(value, row) {
            return row.level === value;
        },
        filterReceiveStatus(value, row) {
            return row.receiveStatus === value;
        },

        // 查看指令
        handleView (index, row) {
            vm.pageTitle = '指令详情'
            vm.isDetail = true
            vm.isAdd = false
            vm.isList = false
            var url = dqurl + 'business/instructions/info/' + row.id
            //ajax
            $.ajax({
            	url : url,//baseURL + 'business/instructions/info/' + row.id,
            	type:'post',
            	dataType:'json',
            	success: function(res){
            		if (res.code === '0') {
            			var data = res.data;
            			// 赋值的同时,若该指令为阅读则起ajax进行阅读
            			if(data.readFlag === '0'&&null != data.targetId){
            				$.ajax({
            					url : dqurl + 'business/instructions/target/read',
            					type:'post',
            					dataType:'json',
            					data:{'id':data.targetId},
	            				success: function(res){

	            				}
            				})
            			}
        				vm.instructionsId = data.id;
        				vm.instructionsTitle = data.titleName;
        				vm.instructionsTime = data.hysj;
        				vm.instructionsUpdateTime = data.createTime;
        				vm.instructionsCorp = data.name;
        				var hysj = new Date(new Date(data.hysjTimes).setHours(0, 0, 0, 0));// 获取0点时间
        				var nowdate = new Date(new Date().setHours(0, 0, 0, 0));// 获取0点时间
        				var flag1 = false;
        				if(nowdate <= hysj){
        					flag1 = true;
        					vm.instructionsStatus = '进行中';
        				}else{
        					vm.instructionsStatus = '已完结';
        				}
        				var flag2 = false;
        				if(data.receiveStatus === '0'){
        					flag2 = true;
        				}
        				if(flag1 && flag2){
	        				if(null != data.userId){
	        					vm.targetId = data.targetId;
	        					$("#qs").show();
	        				}else if(null != data.targetId){
	        					var sessionUser = res.sessionUser;
	        					var roleName = sessionUser.roleName;
	        					if(roleName == 'role1' || roleName == 'role2A' || roleName == 'role3A' || roleName == 'role4A' || roleName == 'role5'){
	        						vm.targetId = data.targetId;
	        						$("#qs").show();
	        					}
	        				}
        				}
        				vm.itemInfos = data.zlxq;
        				vm.getCheckedDw()
        			}else{
        				alert(res.msg);
        				vm.instructionsId = '';
        				vm.instructionsTitle = '';
        				vm.instructionsTime = '';
        				vm.instructionsUpdat = '';
        				vm.instructionsCorp = '';
        				vm.instructionsStatu = '';
        				vm.itemInfos = '';
        			}
            	}
            })
            // 回调函数给对应的数据赋值
        },

        // 获取签收单位信息
        getCheckedDw () {
            // ajax获取数据赋值给qswd
            $.ajax({
             	url : dqurl + 'app/instructions/getInstructionsDept',
             	type:'post',
             	data:{'instructionsId':vm.instructionsId},
             	dataType:'json',
             	success: function(res){
             		if (res.code === '0') {
                        vm.qswd = [].concat(res.data)
                        vm.checkedDw = 0
                        vm.amountDw = 0
                        vm.checkedDWData = []
                        vm.unCheckedDWData = []
                        vm.qswd.forEach(({jszt, deptName, id, userName}) => {
                            vm.amountDw++
                            if (jszt === '1') {
                                vm.checkedDw++
                                vm.checkedDWData.push({
                                    deptName: deptName,
                                    id: id,
                                    jszt: jszt,
                                    userName: userName
                                })
                            } else {
                                vm.unCheckedDWData.push({
                                    deptName: deptName,
                                    id: id,
                                    jszt: jszt,
                                    userName: userName
                                })
                            }
                        })
             		}else{
             			alert(res.msg)
             		}
             	}
        	})
        },

        // 签收指令
        checkInstructions () {
            let params = {
                id: vm.targetId
            }
            $("#qs").attr('style','display:none');
            //    ajax
            $.ajax({
//        		url : baseURL + 'business/instructions/getParentDept',
        		url : dqurl + 'business/instructions/target/update',
        		type : 'post',
        		dataType:'json',
        		data:params,
        		success: function(res){
        			if (res.code === '0') {
        				$("#qs").hide();
        				// 签收按钮消失，已签收列表多了当前签收的部门或人
        				vm.handleView (1, {id:vm.instructionsId});
        			}else{
        				$("#qs").removeAttr('style');
        				alert(res.msg)
        			}
        		}
        	})
        },

        // 切换条线/非条线单位
        changeDwType () {
            const loadingChangeDw = this.$loading({
                lock: true,
                text: '正在刷新单位列表信息，请稍候！',
                target: document.querySelector('.view-tree')
            })
            const loadingChangePerson = this.$loading({
                lock: true,
                text: '正在重置单位下属人员信息，请稍候！',
                target: document.querySelector('.person-view-tree')
            });
            console.log(vm.dwType)
            let url = vm.dwType === 0 ? dqurl + 'business/instructions/getDepts' : dqurl + 'business/instructions/getAllOtherDept'
            //vm.fbfwCheckedList = []
            //vm.fbfwCheckedPersonList = []
            $.ajax({
                url : url,
                type : 'post',
                dataType:'json',
                data:{'sfdctx':'0'},
                success: function(res){
                    if (res.code === '0') {
                        vm.fbfwList = res.data
                        vm.baseForm.dept = []
                        vm.fbfwPersonList = []
                        vm.nowCheckedDw = '未选择单位'
                        loadingChangeDw.close()
                        loadingChangePerson.close()
                    }else{
                        vm.fbfwList = []
                        loadingChangeDw.close()
                        loadingChangePerson.close()
                    }
                    var stemp = [];
                    for(var k in vm.fbfwCheckedList){
                    	stemp.push(vm.fbfwCheckedList[k].deptId)
                    }
                    vm.$refs.fbfwTree.setCheckedKeys(stemp)
                }
            })
        },

        // 新增指令
        addInstructions () {
            console.log(vm.dwType)
            vm.pageTitle = '新增指令'
            vm.isAdd = true
            vm.isList = false
            vm.baseForm = {
                titleName: '',
                msgFlag: 0,
                zlxq: '',
                level: '',
                hysj: '',
                dept: [],
                zlzt: 0
            }
            vm.fbfwCheckedList = []
            vm.fbfwCheckedOnlyList = []
            const loading = this.$loading({
                lock: true,
                text: '正在获取单位列表信息，请稍候！',
                target: document.querySelector('.view-tree')
            });
            $.ajax({
//        		url : baseURL + 'business/instructions/getParentDept',
        		url : dqurl + 'business/instructions/getDepts',
//        		url : baseURL + 'business/instructions/getAllOtherDept',
        		type : 'post',
        		dataType:'json',
        		data:{'sfdctx':'0'},
        		success: function(res){
        			if (res.code === '0') {
        				vm.fbfwList = res.data
                        loading.close()
        			}else{
        				vm.fbfwList = []
                        loading.close()
        			}
        		}
        	})
        },

        checkLength(){
            console.log(vm.baseForm.titleName)
            console.log(vm.baseForm.titleName.length)
            if(vm.baseForm.titleName.length > 16) {
                layer.msg("指令标题长度不能超过16个中文字符")
                return true;
            }
        },

        // 切换短信通知radio状态
        changeMessage (e) {
            e === vm.baseForm.msgFlag ? vm.baseForm.msgFlag = '' : vm.baseForm.msgFlag = e
        },

        // 选择单位
        handleCheckChange (currentNode, allNodes) { // arguments:当前节点 ， 当前选中节点对象
        	var nowDeptId = currentNode.deptId;
        	var flag = true;
            var checkedNodes = vm.$refs.fbfwTree.getCheckedNodes() // 获取选中数据
            var checkedData = checkedNodes.slice(0) // 定义新选中变量不操作原数据
            var checkedArr = [] // 存放选中的节点
            var instructionsIds = [] // 存放选中节点对应的deptId

            for (var i in checkedData) {
            	if(checkedData[i].deptId == nowDeptId){
            		// checkbox为选中状态
            		flag = false;
            	}
                checkedArr.push({
                    label: checkedData[i].label,
                    deptid: checkedData[i].deptid,
                    deptId: checkedData[i].deptId,
                })
                instructionsIds.push({deptId:checkedData[i].deptId || '',userId:checkedData[i].userid || ''})
            }
            vm.fbfwCheckedList = checkedArr
            vm.nowCheckedDw = currentNode.label
            vm.baseForm.dept = instructionsIds
            vm.handleImportPerson(currentNode)
            if(flag){
            	// 如果取消选择当前部门，应把对应的人员删除
            	var temp = [];
            	var temp2 = [];
            	for (var j in vm.fbfwCheckedPersonList) {
            		if(vm.fbfwCheckedPersonList[j].deptId != nowDeptId){
            			temp.push(vm.fbfwCheckedPersonList[j]);
            			temp2.push(vm.formPersonList[j]);
            		}
            	}
            	vm.fbfwCheckedPersonList = temp;
            	vm.formPersonList = temp2;
            	var stemp = [];
                for(var k in vm.fbfwCheckedPersonList){
                	stemp.push(vm.fbfwCheckedPersonList[k].userId)
                }
                vm.$refs.fbfwPersonTree.setCheckedKeys(stemp)
            }
        },

        // 点击单位节点生成下属人员列表
        handleImportPerson (data, nodeObj, node) {debugger
            let deptid = data.deptId
            var checkedNodes = vm.$refs.fbfwTree.getCheckedNodes() // 获取选中数据
            var checkedData = checkedNodes.slice(0) // 定义新选中变量不操作原数据
            var flag = true;
            for (var i in checkedData) {
            	if(checkedData[i].deptId == deptid){
            		// checkbox为选中状态
            		flag = false;
            	}
            }
            if(flag){
            	return
            }
            $.ajax({
                type: "GET",
                url: dqurl + 'app/adds/getSupervisePersons?currPage=0&&pageSize=0&&deptId=' + deptid,
                contentType: "application/json",
                success: function (res) {
                    if (res.code === '0') {
                    	vm.fbfwPersonList =  res.data;// 将模板详情赋值给预览部分的树组件
                        for (var j in vm.fbfwPersonList) {
                            vm.fbfwPersonList[j].label = vm.fbfwPersonList[j].NAME
                            vm.fbfwPersonList[j].deptid = vm.fbfwPersonList[j].DEPT_ID
                            vm.fbfwPersonList[j].userid = vm.fbfwPersonList[j].USER_ID
                            vm.fbfwPersonList[j].deptId = vm.fbfwPersonList[j].DEPT_ID
                            vm.fbfwPersonList[j].userId = vm.fbfwPersonList[j].USER_ID
                        }
                        vm.nowCheckedDw = data.label
                        // 将已选中过的人重新选中
                        var stemp = [];
                        for(var k in vm.fbfwCheckedPersonList){
                        	stemp.push(vm.fbfwCheckedPersonList[k].userId)
                        }
                        vm.$refs.fbfwPersonTree.setCheckedKeys(stemp)
                    } else {
                        alert(res.msg);
                    }
                }
            });
        },

        // 选中单位下属人员
        handlePersonCheckChange (currentNode, allNodes) { // arguments:当前节点 ， 当前选中节点对象
            var checkedNodes = vm.$refs.fbfwPersonTree.getCheckedNodes() // 获取选中数据
            var checkedData = checkedNodes.slice(0) // 定义新选中变量不操作原数据
            var checkedArr = [] // 存放选中的节点
            var instructionsIds = [] // 存放选中节点对应的deptId

            for (var i in checkedData) {
                checkedArr.push({
                    label: checkedData[i].label,
                    deptid: checkedData[i].deptid,
                    deptId: checkedData[i].deptId,
                    userid: checkedData[i].userid,
                    userId: checkedData[i].userId,
                })
                instructionsIds.push({deptId:checkedData[i].deptid || '',userId:checkedData[i].userid || ''})
            }
            
            vm.fbfwCheckedPersonList = mergePerson(vm.fbfwCheckedPersonList,checkedArr,checkedArr[0].deptId)
            vm.formPersonList = mergePerson(vm.formPersonList,instructionsIds,instructionsIds[0].deptId)
        },

        // 取消
        cancel () {
        	var id = $("#id").val()
        	if(id != ''){
        		history.go(-1)
        	}else{
            vm.isAdd = false
            vm.isList = true
            vm.isDetail = false
            vm.baseForm = {
                titleName: '',
                msgFlag: 0,
                zlxq: '',
                level: '',
                hysj: '',
                dept: [],
                zlzt: 0
            }
            vm.fbfwCheckedList = []
            vm.fbfwCheckedOnlyList = []
            vm.fbfwPersonList = []
            vm.fbfwCheckedPersonList = []
            vm.instructionsId = '';
			vm.instructionsTitle = '';
			vm.instructionsTime = '';
			vm.instructionsUpdat = '';
			vm.instructionsCorp = '';
			vm.instructionsStatu = '';
			vm.itemInfos = '';
			vm.dwType = 0;
            console.log(vm.baseForm)
            }
        },

        // 提交审批
        commit () {
            let params = vm.baseForm
            debugger
            params.dept = mergeDeptData(params.dept,vm.formPersonList,'deptId')
            if(params.dept.length == 0){
            	alert('请选择下发部门')
            	return
            }
            if(params.titleName == ''){
            	alert('请输入指令标题')
            	return
            }
            if(params.level == ''){
            	alert('请选择紧急度')
            	return
            }
            if(params.zlxq == ''){
            	alert('请输入指令详情')
            	return
            }
            if(params.hysj == ''){
            	alert('请选择会议时间')
            	return
            }
            params.dept = JSON.stringify(params.dept)
            params.hysj = dateFtt('yyyy-MM-dd hh:mm:ss',params.hysj)
            console.log(params)
//            return false
            $.ajax({
                type: "post",
                url: dqurl + 'business/instructions/save',
                data: JSON.stringify(params),
                contentType: "application/json",
                success: function (res) {
                    if (res.code === '0') {
                        // 成功后的动作
                    	vm.fbfwCheckedList = []
                        vm.fbfwCheckedOnlyList = []
                        vm.fbfwPersonList = []
                        vm.fbfwCheckedPersonList = []
                        vm.instructionsId = '';
            			vm.instructionsTitle = '';
            			vm.instructionsTime = '';
            			vm.instructionsUpdat = '';
            			vm.instructionsCorp = '';
            			vm.instructionsStatu = '';
            			vm.itemInfos = '';
            			vm.dwType = 0;
                        vm.isDetail = false
                        vm.isAdd = false
                        vm.isList = true
                        vm.getData()
                    } else {
                        alert(res.msg);
                    }
                }
            });
        },
    }
})
var id = $("#id").val();
if(id != ''){
	dqurl = '../' + dqurl;
	vm.handleView(0,{'id':id})
}

function mergePerson(arr1,arr2,deptId){
	var temp = [];debugger
	for(var i = 0 ; i < arr1.length ; i ++ ){
		if(arr1[i].deptId != deptId){
			temp.push(arr1[i]);
		}
	}
	temp = temp.concat(arr2);
	return temp;
}


function mergeDeptData(arr1, arr2 ,key){ debugger
	 for (var i = 0 ; i < arr1.length ; i ++ ){
	   for(var j = 0 ; j < arr2.length ; j ++ ){
		if(arr1.length == 0 || arr2.length == 0){
			break;
		}
	    if (arr1[i][key] === arr2[j][key]){
	     arr1.splice(i,1); //利用splice函数删除元素，从第i个位置，截取长度为1的元素
	     i--;
	     break;
	    }
	   }
	 }
	 //alert(arr1.length)
	 arr1 = arr1.concat(arr2);
	 return arr1;
	}